package com.ssm.wechat.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ssm.util.object.InputObject;
import com.ssm.util.object.OutputObject;
import com.ssm.wechat.dao.WechatUserDao;
import com.ssm.wechat.service.GetWechatUserInfo;
import com.ssm.wechat.service.GetWechatUserList;
import com.ssm.wechat.service.WechatUserService;

@Service
public class WechatUserServiceImpl implements WechatUserService {

	@Autowired
	private WechatUserDao wechatUserDao;

	/**
	 * 订阅公众号
	 */
	@Override
	public void subscribe(String openid) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("openid", openid);
		//查询关注的用户是否已经存在,判断当前状态是关注还是取消关注
		Map<String, Object> bean = wechatUserDao.queryWechatUserSubscribe(map);
		System.out.println(bean);
		if(bean != null){
			if(bean.get("subscribe").toString().equals("0")){
				map.put("subscribe", 1);
				//更新已经存在的用户，但未关注，修改为关注状态
				wechatUserDao.updateWechatUserSubscribe(map);
			}
		}else{
			//获取当前关注用户的基本信息
			map = GetWechatUserInfo.getRequest1(openid);
			System.out.println(map);
			//增加关注公众号的用户信息
			wechatUserDao.addWechatUser(map);
		}
	}

	/**
	 * 取消订阅公众号
	 */
	@Override
	public void unsubscribe(String openid) throws Exception {
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("openid", openid);
		map.put("subscribe", 0);
		wechatUserDao.updateWechatUserSubscribe(map);
	}

	/**
	 * 检查微信公众号中已经关注的用户，获取并存储到数据库中
	 * @throws Exception 
	 */
	@Override
	public void checkWechatUserByList(InputObject inputObject, final OutputObject outputObject) throws Exception {
		Map<String, Object> map = inputObject.getLogParams();
		//获取微信用户列表
		List<String> wechatUserList = GetWechatUserList.getRequest();
		//查询已存储的用户的openid
		List<Map<String, Object>> beans = wechatUserDao.queryWechatUserOpenid();
		List<Map<String, Object>> params = new ArrayList<Map<String, Object>>();
		
		//判断获取到的openid是否已经存在，存在移除
		for(int i=0;i<beans.size();i++)
		{
			if(wechatUserList.contains(beans.get(i).get("openid").toString())){
				wechatUserList.remove(beans.get(i).get("openid").toString());
			}
		}
		List<Map<String, Object>> wechatUsers = new ArrayList<Map<String, Object>>();
		while(!wechatUserList.isEmpty()){
			//将openid添加到Map集合中
			for(int j = 0;j < wechatUserList.size() && !wechatUserList.isEmpty();j++){
				Map<String,Object> param = new HashMap<String, Object>();
				param.put("openid", wechatUserList.get(0));
				params.add(param);
				wechatUserList.remove(0);
			}
			//根据openid获取微信用户信息
			wechatUsers.addAll(GetWechatUserInfo.getRequest(params));
			params.clear();
			
		}
		for(int i=0;i<wechatUsers.size();i++){
			wechatUserDao.addWechatUser(wechatUsers.get(i));
		}
	}

	
}
